package me.like.diandian.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.viewpager.widget.PagerAdapter;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

import me.like.diandian.R;
import me.like.diandian.activity.ExploreActivity;
import me.like.diandian.bean.BannerListBean;

/**
 * Created by shousakai on 2019/6/22.
 */

public class HomePagerAdapter extends PagerAdapter {
    private List<BannerListBean> listBeans;
    private List<View> imageViews;

    public HomePagerAdapter(Context context, List<BannerListBean> listBeans) {
        this.listBeans = listBeans;
        imageViews = new ArrayList<>();
        for (BannerListBean bean : listBeans) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.item_image, null);
            ImageView imageView = inflate.findViewById(R.id.iv_image);
            Glide.with(context).load(bean.getPicUrl()).into(imageView);
            imageView.setOnClickListener(v -> {
                ExploreActivity.startActivity(context, bean.getJumpUrl(), bean.getBannerName());
            });
            imageViews.add(inflate);
        }
    }

    @Override
    public int getCount() {
        return listBeans.size();
    }


    // 来判断显示的是否是同一张图片，这里我们将两个参数相比较返回即可
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        return arg0 == arg1;
    }

    // PagerAdapter只缓存三张要显示的图片，如果滑动的图片超出了缓存的范围，就会调用这个方法，将图片销毁
    @Override
    public void destroyItem(ViewGroup view, int position, Object object) {
        view.removeView(imageViews.get(position));
    }

    // 当要显示的图片可以进行缓存的时候，会调用这个方法进行显示图片的初始化，我们将要显示的ImageView加入到ViewGroup中，然后作为返回值返回即可
    @Override
    public Object instantiateItem(ViewGroup view, int position) {
        view.addView(imageViews.get(position));
        return imageViews.get(position);
    }
}
